import { useState, useEffect, Fragment } from 'react';
import { AppGlobalEffects, useEnv, arms } from '@ydc/workbench-tools';
import { AppLayout } from '@ydc/workbench-ui';
import { Alert, Skeleton, Spin } from 'antd';
import BuiltPageRenderer from '@/components/ydcBuiltPageRenderer';
import { renderWidget } from '@ydc/ui-renderer';
import * as pages from '@/pages';
import _ from 'lodash';

enum PageState {
  Loading,
  Error,
  Ready,
}

export default function FirstPartyAppLayout() {
  const { env } = useEnv();
  const [pageState, setPageState] = useState(PageState.Loading);
  const [pageName, setPageName] = useState<string>();

  window._vars_ = {
    locoMaterialVersions: {
      '@ydc/loco-ui': 'daily',
    },
  };

  useEffect(() => {
    if (env.page && env.page.schemaVersion !== '2') {
      const content = JSON.parse(env.page?.pageContent);
      if (content.root.version !== '1.0.x') {
        try {
          const pageSchema = JSON.parse(env.page.pageContent);
          const rootComponent: string = _.get(pageSchema, 'root.component');
          const nextPageName = _.last(rootComponent.split('/'));
          if (!nextPageName) {
            throw new Error('未找到该页面对应的组件名, 请检查 JSON Schema 是否正确');
          }
          if (!_.has(pages, nextPageName)) {
            throw new Error(`在该应用中未找到名为 ${nextPageName} 的组件, 请检查名称是否正确`);
          }
          setPageName(nextPageName);
          setPageState(PageState.Ready);
        } catch (error) {
          console.error(error);
          setPageState(PageState.Error);
          arms.reportError(error as Error);
        }
      } else {
        setPageState(PageState.Loading);
      }
    }
  }, [env.page]);

  let contentElement;

  if (pageState === PageState.Error) {
    contentElement = <Alert showIcon type="error" message={`页面发生错误: 请查看控制台`} />;
  } else if (pageState === PageState.Loading) {
    contentElement = (
      <Spin size="large" tip="正在加载页面...." style={{ height: '100vh' }}>
        <Skeleton />
      </Spin>
    );
  } else {
    const Page = _.get(pages, pageName!);
    contentElement = <Page />;
  }

  if (env.page?.schemaVersion === '2') {
    contentElement = <BuiltPageRenderer schema={env.page.pageContent} />;
  }

  if (env.page) {
    const content = JSON.parse(env.page?.pageContent);
    if (content.root.version === '1.0.x') {
      contentElement = (
        <Fragment>
          {renderWidget(JSON.parse(env.page.pageContent), {
            // 传给渲染引擎的数据
            env: {
              app: env?.app,
              portalApp: env?.portalApp,
              tenant: env?.tenant,
              user: env?.user,
              permission: env?.permission,
              innerWidth: window.innerWidth,
              innerHeight: window.innerHeight,
              isPrint: false,
              screen,
              ...env,
              mode: 'development',
            },
          })}
        </Fragment>
      );
    }
  }

  return (
    <>
      <AppLayout>
        {/* <AppGlobalEffects appCode="HR_ATS" appEnv={APP_ENV} armsEnabled={ARMS_ENABLED} /> */}
        {contentElement}
      </AppLayout>
    </>
  );
}
